package com.hundun.hddeal.controller;


import com.aliyuncs.exceptions.ClientException;
import com.google.common.base.Objects;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.hundun.hddeal.dao.*;
import com.hundun.hddeal.entity.*;
import com.hundun.hddeal.response.Result;
import com.hundun.hddeal.response.ResultUtil;
import com.hundun.hddeal.service.FeedbackService;
import com.hundun.hddeal.service.lmpl.AdUserServiceImpl;
import com.hundun.hddeal.service.lmpl.MtUserServiceImpl;
import com.hundun.hddeal.service.lmpl.OrderDetailServiceImpl;
import com.hundun.hddeal.service.lmpl.RecordServiceImpl;
import com.hundun.hddeal.util.*;
import com.hundun.hddeal.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;
import static org.assertj.core.util.DateUtil.now;


/**
 * 预约公众号接口
 * @author 谢
 */
@CrossOrigin
@RestController
@RequestMapping("order")
@Slf4j
public class OrderController {

    @Autowired
    MtUserServiceImpl mtUserService;
    @Autowired
    AdUserServiceImpl adUserService;
    @Autowired
    GzhMapper gzhMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    OrderDetailServiceImpl orderDetailService;
    @Autowired
    PicMapper picMapper;
    @Autowired
    FeedbackService feedbackService;
    @Autowired
    AdUserMapper adUserMapper;
    @Autowired
    MtUserMapper mtUserMapper;
    @Autowired
    RecordServiceImpl recordService;
    @Autowired
    RecordMapper recordMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    RedisUtil redisUtil;


    /**
     * 增加订单
     * @param gzhVo
     * @return
     */
    @PostMapping("add")
    public Result addOrder(@RequestBody GzhVo gzhVo){
        //生成主id
        String hostId = OrderIdUtil.OrderNum();
        String token = gzhVo.getAdUserToken();
        Double moneySum = 0.00;
        Integer gzhFansSum = 0;
        String adUserId = TokenUtilT.getTokenById(token);
        AdUser adUser = adUserService.findAdUserById(adUserId);
        if (adUser != null) {
            String[] ghIds = gzhVo.getGhIds();

            //预约则删除购物车
            List<Gzh> list= (List<Gzh>) redisUtil.get(adUser.getAdId());
            List <Gzh> gzhList= gzhMapper.selectByGhIds(gzhVo.getGhIds());
            for (Gzh gzh:gzhList) {
                for(int i=0;i<list.size();i++){
                    //如果ghid相同则删除
                    if(gzh.getGhId().equals(list.get(i).getGhId())){
                        list.remove(list.get(i));
                    }
                }
            }
            redisUtil.set(adUser.getAdId(),list);


            int length = ghIds.length;
            StringBuilder buf = new StringBuilder();
            for (String ghId : ghIds) {
                Gzh gzh = gzhMapper.selectByGhId(ghId);
                OrderDetail orderDetail = orderDetailMapper.getOrederGzh(gzh.getGhId(), gzhVo.getTgTime(), gzhVo.getPlace());
                gzhFansSum += gzh.getGzhFans();
                //添加至大表
                if ("多图文头条".equals(gzhVo.getPlace())) {
                    moneySum += gzh.getPriceFirst();
                } else {
                    moneySum += gzh.getPriceSecond();
                }

                if (orderDetail != null) {
                    if (orderDetail.getStatus() != 7 || orderDetail.getStatus() != 8) {
                        buf.append(gzh.getGzhName()).append(",");
                    }

                }
            }

            if (buf.length()!=0) {
                return ResultUtil.error("该日期的如下公众号已被预约:" + "" + buf.toString());
            }

            Order order = new Order();
            order.setAdId(adUserId);
            order.setHostId(hostId);
            order.setOrderMoney(moneySum);
            order.setNeedName(gzhVo.getNeedName());
            order.setOrderInfo(gzhVo.getOrderInfo());
            order.setPlace(gzhVo.getPlace());
            order.setBackTime(gzhVo.getBackTime());
            order.setHyType(gzhVo.getHyType());
            order.setTgTime(gzhVo.getTgTime());
            order.setTextTitle(gzhVo.getTextTitle());
            order.setTextUrl(gzhVo.getTextUrl());
            order.setGzhFans(gzhFansSum);
            order.setGzhNum(length);
            //base64编码
            Base64.Encoder encoder = Base64.getEncoder();
            byte[] textByte = gzhVo.getTextBody().getBytes(StandardCharsets.UTF_8);
            String encodedText = encoder.encodeToString(textByte);
            order.setTextBody(encodedText);

            order.setImportText(gzhVo.getImportText());
            order.setUserFz(adUser.getFz());
            order.setUserName(adUser.getUserName());
            order.setDitchFz(adUser.getFz());
            order.setDitchName(adUser.getUserName());
            order.setStatus((byte) 0);
            order.setPlace(gzhVo.getPlace());
            order.setPicture1(gzhVo.getPicture1());
            orderMapper.insertSelective(order);
            ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("thread-call-runner-%d").build();
            ExecutorService fixedThreadPool = new ThreadPoolExecutor(length, length,0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1024),namedThreadFactory);
            //获取当前时间
            Date curDate = new Date(System.currentTimeMillis());
            for (int i = 0; i < length; i++) {
                //生成订单号
                String orderId = OrderIdUtil.OrderNum();
                final int index = i;
                fixedThreadPool.execute(() -> {
                    Gzh gzh = gzhMapper.selectByGhId(ghIds[index]);
                    MtUser mtUser = mtUserService.selectById(gzh.getGzhId());
                    //订单
                    OrderDetail orderDetail = new OrderDetail();
                    orderDetail.setOrderId(orderId);
                    if (Objects.equal("多图文头条", gzhVo.getPlace())) {
                        orderDetail.setOrderMoney(gzh.getPriceFirst());
                    } else if (Objects.equal("多图文非头条", gzhVo.getPlace())) {
                        orderDetail.setOrderMoney(gzh.getPriceSecond());
                    }
                    orderDetail.setCreateDate(curDate);
                    orderDetail.setAdId(adUser.getAdId());
                    orderDetail.setMtId(mtUser.getMtId());
                    orderDetail.setGhId(gzh.getGhId());
                    orderDetail.setGzhFans(gzh.getGzhFans());
                    orderDetail.setNeedName(gzhVo.getNeedName());
                    orderDetail.setHyType(gzhVo.getHyType());
                    orderDetail.setPlace(gzhVo.getPlace());
                    orderDetail.setTgTime(gzhVo.getTgTime());
                    orderDetail.setBackTime(gzhVo.getBackTime());
                    orderDetail.setImportText(gzhVo.getImportText());
                    orderDetail.setSummary(gzhVo.getSummary());
                    orderDetail.setTextBody(encodedText);
                    orderDetail.setTextTitle(gzhVo.getTextTitle());
                    orderDetail.setTextUrl(gzhVo.getTextUrl());
                    orderDetail.setPicture1(gzhVo.getPicture1());
                    orderDetail.setPicture2(gzhVo.getPicture2());
                    orderDetail.setPicture3(gzhVo.getPicture3());
                    orderDetail.setProve(gzhVo.getProve());
                    orderDetail.setGzhName(gzh.getGzhName());
                    orderDetail.setOrderInfo(gzhVo.getOrderInfo());
                    orderDetail.setRealityTgTime(gzhVo.getRealityTgTime());
                    orderDetail.setRealityTime(gzhVo.getRealityTime());
                    orderDetail.setRetentionTime(gzhVo.getRetentionTime());
                    orderDetail.setHostId(hostId);
                    orderDetail.setUserFz(adUser.getFz());
                    orderDetail.setUserName(adUser.getUserName());
                    orderDetail.setDitchFz(adUser.getFz());
                    orderDetail.setDitchName(adUser.getUserName());
                    orderDetailMapper.insertSelective(orderDetail);
                });

            }
            fixedThreadPool.shutdown();
            return ResultUtil.success();
        }
        return ResultUtil.error("无token");
    }


    /**
     * 查询广告用户订单列表
     * @param adUserVo
     * @return
     */
    @PostMapping("ad")
    public Result getAdUserOrder(@RequestBody AdUserVo adUserVo) {
        String adUserId = TokenUtilT.getTokenById(adUserVo.getAdUserToken());
        AdUser adUser = adUserService.findAdUserById(adUserId);
        if (adUserVo.getStatus() == null) {
            adUserVo.setStatus((byte) 9);
        }
        if (adUser != null) {
            return orderDetailService.getAll(adUser.getAdId(), adUserVo.getStatus(), adUserVo.getPageNum(), adUserVo.getPageSize()
                    , adUserVo.getNeedName(), adUserVo.getStartTime(), adUserVo.getEndTime(), adUserVo.getHostId(), adUserVo.getOrderId(), adUserVo.getGzhName());
        }
        return ResultUtil.error();
    }


    /**
     * 查询媒体用户订单列表
     * @param mtUserVo
     * @return
     */
    @PostMapping("mt")
    public Result getMdUserOrder(@RequestBody MtUserVo mtUserVo){
        String mtUserId = TokenUtilT.getTokenById(mtUserVo.getMtUserToken());
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        if (mtUserVo.getStatus() == null) {
            mtUserVo.setStatus((byte) 9);
        }
        if (mtUser != null) {
            return orderDetailService.getAll1(mtUser.getMtId(), mtUserVo.getStatus(),
                    mtUserVo.getPageNum(), mtUserVo.getPageSize(), mtUserVo.getOrderId(), mtUserVo.getNeedName(), mtUserVo.getGzhName(),
                    mtUserVo.getStartTime(), mtUserVo.getEndTime(), mtUserVo.getHostId());
        }
        return ResultUtil.error();
    }


    /**
     * 媒体方导出要批量上传的预览链接订单表
     * @param
     * @return
     */
    @GetMapping("exportOrderLookUrl")
    public void exportOrderLookUrl(@RequestParam("mtUserToken") String token, @RequestParam("hostId") String hostId, HttpServletResponse response) throws IOException {
        String mtUserId = TokenUtilT.getTokenById(token);
        List<OrderDetail> orderDetails = orderDetailMapper.selectByMtIdAndStatus(mtUserId, 2,
                null, null, null, null, null, hostId);
        EasyPoiUtil.exportExcel(orderDetails,null,"sheet1",OrderDetail.class,"预览链接数据表.xls",true,response);
    }

    /**
     * 媒体方导出要批量上传的执行链接订单表
     * @param
     * @return
     */
    @GetMapping("exportOrderTakeUrl")
    public void exportOrderTakeUrl(@RequestParam("mtUserToken") String token, @RequestParam("hostId") String hostId, HttpServletResponse response) throws IOException {
        String mtUserId = TokenUtilT.getTokenById(token);
        List<OrderDetail> orderDetails = orderDetailMapper.selectByMtIdAndStatus(mtUserId, 5,
                null, null, null, null, null, hostId);
        EasyPoiUtil.exportExcel(orderDetails,null,"sheet1",OrderDetail.class,"执行链接数据表.xls",true,response);
    }


    /**
     * 媒体方导入要批量上传的预览链接订单表
     * @param
     * @return
     */
    @PostMapping("importOrderLookUrl")
    public Result importOrderLookUrl(@RequestParam("mtUserToken") String token, @RequestParam("file") MultipartFile file){
        String mtUserId = TokenUtilT.getTokenById(token);
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        if (mtUser != null) {
            List<OrderDetail> orderDetails = EasyPoiUtil.importExcel(file,0,1,OrderDetail.class);
            StringBuilder buf = new StringBuilder();
            for (OrderDetail orderDetail : orderDetails) {
                if(orderDetail.getLookUrl()!=null){
                    orderDetail.setStatus((byte) 4);
                    orderDetail.setTakeUrl(null);
                    orderDetail.setUpdateDate(now());
                    orderDetailMapper.updateByPrimaryKey(orderDetail);
                }else {
                    buf.append(orderDetail.getGzhName()).append(",");
                }
            }
            if (buf.length()!=0) {
                return ResultUtil.error(buf.toString()+"该订单上传预览链接有误，请核实后再上传!");
            }
            return ResultUtil.success();
        }
        return ResultUtil.error();
    }


    /**
     * 媒体方导入要批量上传的执行链接订单表
     * @param
     * @return
     */
    @PostMapping("importOrderTakeUrl")
    public Result importOrderTakeUrl(@RequestParam("mtUserToken") String token, @RequestParam("file") MultipartFile file){
        String mtUserId = TokenUtilT.getTokenById(token);
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        if (mtUser != null) {
            List<OrderDetail> orderDetails = EasyPoiUtil.importExcel(file,0,1,OrderDetail.class);
            StringBuilder buf = new StringBuilder();
            for (OrderDetail orderDetail : orderDetails) {
                if(orderDetail.getTakeUrl()!=null){
                    orderDetail.setStatus((byte) 6);
                    orderDetail.setLookUrl(null);
                    orderDetail.setUpdateDate(now());
                    orderDetailMapper.updateByPrimaryKey(orderDetail);
                }else {
                    buf.append(orderDetail.getGzhName()).append(",");
                }
            }
            if (buf.length()!=0) {
                return ResultUtil.error(buf.toString()+"该订单上传执行链接有误，请核实后再上传!");
            }
            return ResultUtil.success();
        }
        return ResultUtil.error();
    }


    /**
     * 保存预览图片并更改订单状态
     */
    @PostMapping("save")
    public Result savePvw(@RequestBody PreviewVo previewVo) {
        String orderId = previewVo.getOrderId();
        String preview = previewVo.getPreview();
        if (orderId != null || preview != null) {
            OrderDetail orderDetail = orderDetailMapper.selectByOrderId(orderId);
            orderDetail.setPreview(preview);
            orderDetail.setStatus((byte) 2);
            orderDetailMapper.updateByPrimaryKey(orderDetail);
            return ResultUtil.success(orderDetail);
        }
        return ResultUtil.error();
    }

    /**
     * 订单状态更改
     */
    @PostMapping("change")
    public Result change(@RequestBody PreviewVo previewVo) {
        String orderId = previewVo.getOrderId();
        if (orderId != null) {
            OrderDetail orderDetail = orderDetailMapper.selectByOrderId(orderId);
            int status = orderDetail.getStatus();
            int statu = status + 1;
            if (statu <= 6) {
                orderDetail.setStatus((byte) statu);
                orderDetailMapper.updateByPrimaryKey(orderDetail);
                return ResultUtil.success(orderDetail);
            }
            return ResultUtil.error(300, "状态不能更改");
        }
        return ResultUtil.error();
    }


    /**
     * 付款图片
     * @return
     */
    @GetMapping("getpic")
    public Result getPic() {
        Pic pic = picMapper.selectByPrimaryKey((long) 1);
        log.info(pic.getPic());
        return ResultUtil.isok(pic.getPic());
    }


    /**
     * 预览图片
     * @param orderVo
     * @return
     */
    @PostMapping("pvw")
    public Result getPvw(@RequestBody OrderVo orderVo) {
        OrderDetail orderDetail = orderDetailMapper.selectByOrderId(orderVo.getOrderId());
        if (orderDetail != null) {
            return ResultUtil.isok(orderDetail.getPreview());
        }
        return ResultUtil.error();
    }


    /**
     * 广告之后审核图片保存
     *
     * @param orderVo
     * @return
     */
    @PostMapping("checkpic")
    public Result getCheckPic(@RequestBody OrderVo orderVo) {
        OrderDetail orderDetail = orderDetailMapper.selectByOrderId(orderVo.getOrderId());
        if (orderDetail != null) {
            orderDetail.setCheckPic(orderVo.getCheckPic());
            orderDetailMapper.updateByPrimaryKeySelective(orderDetail);
            return ResultUtil.success(orderDetail);
        }
        return ResultUtil.error();
    }


    /**
     * 计算图文位置的金额
     *
     * @param gzhVo
     * @return
     */
    @PostMapping("moneySum")
    public Result moneySum(@RequestBody GzhVo gzhVo) {
        String token = gzhVo.getAdUserToken();
        String adUserId = TokenUtilT.getTokenById(token);
        AdUser adUser = adUserService.findAdUserById(adUserId);
        if (adUser != null) {
            String[] ghIds = gzhVo.getGhIds();
            Double sum = 0.0;
            for (int i = 0; i < ghIds.length; i++) {
                Gzh gzh = gzhMapper.selectByGhId(ghIds[i]);
                if ("多图文头条".equals(gzhVo.getPlace())) {
                    sum += gzh.getPriceFirst();
                } else if ("多图文非头条".equals(gzhVo.getPlace())) {
                    sum += gzh.getPriceSecond();
                }
            }
            //Double admoney = adUser.getAdMoney();
            BigDecimal b = new BigDecimal(sum);
            double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            /*if (admoney < sum) {
                return ResultUtil.error("", "账户余额不足");
            }*/
            return ResultUtil.success(100, "操作成功", f1);
        }

        return ResultUtil.error("无token");

    }


    /**
     * 媒体查询各个订单状态的条数
     */
    @PostMapping("getAllStatus")
    public Result getAllStatus(@RequestBody Map<String, String> map) {
        String mtUserId = TokenUtilT.getTokenById(map.get("mtUserToken"));
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        if (mtUser != null) {
            try {
                StatusCountVo statusCountVo = orderDetailMapper.selectAllStatus(mtUser.getMtId(), null, map.get("hostId"));
                return ResultUtil.success(statusCountVo);
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.error();
            }
        }
        return ResultUtil.error("无token");

    }


    /**
     * 广告查询各个订单状态的条数
     */
    @PostMapping("getAdStatus")
    public Result getAdStatus(@RequestBody Map<String, String> map) {
        String adUserId = TokenUtilT.getTokenById(map.get("adUserToken"));
        AdUser adUser = adUserMapper.selectByAdUserId(adUserId);
        if (adUser != null) {
            try {
                StatusCountVo statusCountVo = orderDetailMapper.selectAllStatus(null, adUserId, map.get("hostId"));
                return ResultUtil.success(statusCountVo);
            } catch (Exception e) {
                e.printStackTrace();
                return ResultUtil.error();
            }
        }
        return ResultUtil.error("无token");

    }


    /**
     * 媒体广告获取单个订单
     *
     * @param map
     * @return
     */
    @PostMapping("getOrderOne")
    public Result getOrderOne(@RequestBody Map<String, String> map) {
        String mttoken = map.get("mtUserToken");
        String adtoken = map.get("adUserToken");
        if (mttoken != null) {
            String mtUserId = TokenUtilT.getTokenById(mttoken);
            MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
            if (mtUser != null) {
                return orderDetailService.selectByPrimaryKey(Long.parseLong(map.get("id")));
            }
            return ResultUtil.error("无token!");
        }
        if (adtoken != null) {
            String adUserId = TokenUtilT.getTokenById(adtoken);
            AdUser adUser = adUserMapper.selectByAdUserId(adUserId);
            if (adUser != null) {
                return orderDetailService.selectByPrimaryKey(Long.parseLong(map.get("id")));
            }
            return ResultUtil.error("无token!");
        }
        return ResultUtil.success();
    }

    /**
     * 媒体||广告改变订单状态
     * @param requestPageBean
     * @return
     */
    @PostMapping("setStatus")
    public Result updateOrderMtStatus(@RequestBody RequestPageBean requestPageBean) {
        String mttoken = requestPageBean.getMtUserToken();
        String adtoken = requestPageBean.getAdUserToken();
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setStatus(requestPageBean.getStatus());
        orderDetail.setIds(requestPageBean.getIds());
        List<OrderDetail> orderDetails = orderDetailMapper.idsOrder(requestPageBean.getIds());
        if (mttoken != null) {
            String mtUserId = TokenUtilT.getTokenById(mttoken);
            MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
            if (mtUser == null) {
                return ResultUtil.error("不存在该用户!");
            }
                for (OrderDetail orderDetail1 : orderDetails) {

                    if (requestPageBean.getStatus() == 7 && orderDetail1.getStatus()==1) {
                    adUserMapper.updateIceMoney(orderDetail1.getAdId(), -orderDetail1.getOrderMoney());
                    adUserMapper.updateMoney(orderDetail1.getAdId(), -orderDetail1.getOrderMoney());
                    Record record = new Record();
                    record.setUserId(orderDetail1.getAdId());
                    record.setOrderId(orderDetail1.getOrderId());
                    record.setStatus((byte) 2);
                    record.setMoney(orderDetail1.getOrderMoney());
                    record.setYyName(orderDetail1.getNeedName());
                    record.setGzhName(orderDetail1.getGzhName());
                    record.setUpdateDate(now());
                    record.setContent("退款记录");
                    record.setUserFz(orderDetail1.getUserFz());
                    record.setUserName(orderDetail1.getUserName());
                    recordMapper.insertSelective(record);

                    Feedback feedback = new Feedback();
                    feedback.setOrder(orderDetail1.getOrderId());
                    feedback.setMessage(requestPageBean.getMessage());
                    feedback.setMtId(mtUserId);
                    feedbackService.insertSelective(feedback);
                    //-1则不修改状态
                    orderMapper.updateStatus((byte)-1, orderDetail1.getHostId(),orderDetail1.getOrderMoney());
                }else if(!(requestPageBean.getStatus() == 2 && orderDetail1.getStatus()==1)){
                        return ResultUtil.error("当前有订单状态不可修改!");
                }
            }
            return orderDetailService.updateByPrimaryKeySelective(orderDetail);

        } else if (adtoken != null) {
            String adUserId = TokenUtilT.getTokenById(adtoken);
            AdUser adUser = adUserMapper.selectByAdUserId(adUserId);
            if (adUser == null) {
                return ResultUtil.error("无token!");
            }

                for (OrderDetail orderDetail1 : orderDetails) {

                    if (requestPageBean.getStatus() == 7 && orderDetail1.getStatus()==4) {
                    Feedback feedback = new Feedback();
                    feedback.setOrder(orderDetail1.getOrderId());
                    feedback.setMessage(requestPageBean.getMessage());
                    feedback.setMtId(adUserId);
                    feedbackService.insertSelective(feedback);
                   }else if(!(requestPageBean.getStatus() == 5 && orderDetail1.getStatus()==4)){
                        return ResultUtil.error("当前有订单状态不可修改!");
                    }
            }
            return orderDetailService.updateByPrimaryKeySelective(orderDetail);
        }
        return ResultUtil.error();
    }

    /**
     * 媒体添加预览链接和执行链接
     *
     * @param map
     * @return
     */
    @PostMapping("setUrl")
    public Result setUrl(@RequestBody Map<String, String> map) {
        String mtUserId = TokenUtilT.getTokenById(map.get("mtUserToken"));
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        if (mtUser != null) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setLookUrl(map.get("lookUrl"));
            orderDetail.setTakeUrl(map.get("takeUrl"));
            orderDetail.setId(Long.parseLong(map.get("id")));
            orderDetail.setStatus((byte) Integer.parseInt(map.get("status")));
            return orderDetailService.updateByPrimaryKeySelective(orderDetail);
        }
        return ResultUtil.error("无token!");
    }


    /**
     * 媒体方查询订单反馈列表
     *
     * @param map
     * @return
     */
    @PostMapping("mtBack")
    public Result getAllbackBymt(@RequestBody Map<String, String> map) {
        String mtUserId = TokenUtilT.getTokenById(map.get("mtUserToken"));
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        if (mtUser != null) {
            return feedbackService.getAllBymt(Integer.parseInt(map.get("pageNum")), Integer.parseInt(map.get("pageSize")),
                    map.get("orderId"));
        }
        return ResultUtil.error("无token!");
    }

    /**
     * 广告方查询订单反馈
     *
     * @param map
     * @return
     */
    @PostMapping("adBack")
    public Result getAdback(@RequestBody Map<String, String> map) {
        String token = map.get("adUserToken");
        String adUserId = TokenUtilT.getTokenById(token);
        AdUser adUser = adUserService.findAdUserById(adUserId);
        if (adUser != null) {
            return feedbackService.getAllBymt(Integer.parseInt(map.get("pageNum")), Integer.parseInt(map.get("pageSize")),
                    map.get("orderId"));
        }
        return ResultUtil.error();
    }


    /**
     * 广告方添加订单反馈到媒体方
     * @param adUserVo
     * @return
     */
    @PostMapping("setBack")
    public Result setBackForMt(@RequestBody AdUserVo adUserVo) {
        String token = adUserVo.getAdUserToken();
        String adUserId = TokenUtilT.getTokenById(token);
        AdUser adUser = adUserService.findAdUserById(adUserId);
        if (adUser != null) {
            List<OrderDetail> orderDetails = orderDetailMapper.idsOrder(adUserVo.getIds());
            for (OrderDetail orderDetail:orderDetails) {
                if(!(adUserVo.getStatus()==2&&orderDetail.getStatus()==4)){
                    return ResultUtil.error("当前有订单状态不可修改!");
                }
            }
            String[] orderIds = adUserVo.getOrderIds();
            for (String orderId : orderIds) {
                Feedback feedback = new Feedback();
                feedback.setOrder(orderId);
                feedback.setMessage(adUserVo.getMessage());
                feedback.setAdId(adUserId);
                feedbackService.insertSelective(feedback);
            }
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setStatus(adUserVo.getStatus());
            orderDetail.setIds(adUserVo.getIds());
            return orderDetailService.updateByPrimaryKeySelective(orderDetail);

        }
        return ResultUtil.error();
    }


    /**
     * 预约时查看公众号是否被预约档期中
     * @param gzhVo
     * @return
     */
    @PostMapping("istakeOrder")
    public Result istakeOrder(@RequestBody GzhVo gzhVo) {
        String token = gzhVo.getAdUserToken();
        String adUserId = TokenUtilT.getTokenById(token);
        Double sum = 0.0;
        AdUser adUser = adUserService.findAdUserById(adUserId);
        if (adUser != null) {
            String[] ghIds = gzhVo.getGhIds();
            List<String> ghids = new ArrayList<>(Arrays.asList(ghIds));
            List<String> list = new ArrayList<>();
            StringBuilder buf = new StringBuilder();
            for (String ghId : ghIds) {
                Gzh gzh = gzhMapper.selectByGhId(ghId);
                OrderDetail orderDetail = orderDetailMapper.getOrederGzh(gzh.getGhId(), gzhVo.getTgTime(), gzhVo.getPlace());
                if (orderDetail != null) {
                    list.add(gzh.getGhId());
                    ghids.remove(gzh.getGhId());
                    buf.append(gzh.getGzhName()).append(",");
                }
            }

            //重新计算总价
            for (String ghid : ghids) {
                Gzh gzh = gzhMapper.selectByGhId(ghid);
                if ("多图文头条".equals(gzhVo.getPlace())) {
                    sum += gzh.getPriceFirst();
                } else if ("多图文非头条".equals(gzhVo.getPlace())) {
                    sum += gzh.getPriceSecond();
                }
            }
            BigDecimal b = new BigDecimal(sum);
            double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            if (list.size() != 0) {
                return ResultUtil.error("该日期的公众号已被预约:"+ buf.toString(), list, f1);
            } else {
                return ResultUtil.success("操作成功",f1);
            }
        }
        return ResultUtil.error("无token");
    }


    /**
     * 媒体主hostId订单首页
     *
     * @param mtUserVo
     * @return
     */
    @PostMapping("mtHostList")
    public Result newOrder(@RequestBody MtUserVo mtUserVo) {
        String mtUserId = TokenUtilT.getTokenById(mtUserVo.getMtUserToken());
        MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
        if (mtUser != null) {
            return orderDetailService.mtHostList(mtUserId, mtUserVo.getPageNum(), mtUserVo.getPageSize(),
                    mtUserVo.getHostId(), mtUserVo.getNeedName(), mtUserVo.getStartTime(), mtUserVo.getEndTime(),mtUserVo.getStatus());
        }
        return ResultUtil.error("无token!");
    }

    /**
     * 广告主hostId订单首页
     *
     * @param adUserVo
     * @return
     */
    @PostMapping("adHostList")
    public Result newOrder(@RequestBody AdUserVo adUserVo) {
        String adUserId = TokenUtilT.getTokenById(adUserVo.getAdUserToken());
        AdUser adUser = adUserMapper.selectByAdUserId(adUserId);
        if (adUser != null) {
            return orderDetailService.adHostList(adUserId, adUserVo.getPageNum(), adUserVo.getPageSize(),
                    adUserVo.getHostId(), adUserVo.getNeedName(), adUserVo.getStartTime(), adUserVo.getEndTime(),adUserVo.getStatus());
        }
        return ResultUtil.error("无token!");
    }


    /**
     * 广告订单付款
     * @param gzhVo
     * @return
     */
    @PostMapping("orderPay")
    public Result orderPay(@RequestBody GzhVo gzhVo) throws ClientException {
        String adUserId = TokenUtilT.getTokenById(gzhVo.getAdUserToken());
        AdUser adUser = adUserService.findAdUserById(adUserId);
        if (adUser != null) {

            //判断支付密码是否正确
            if(!MD5Util.getSaltverifyMD5(gzhVo.getPayPwd(),adUser.getPayPwd())){
                return ResultUtil.error("支付密码不正确");
            }

            //扣除广告方账户金额及冻结生成冻结记录消费记录
            List<OrderDetail> orderDetails = orderDetailMapper.getDetails(gzhVo.getHostId(), adUserId, null);
            Double moneySum = 0.00;
            for (OrderDetail orderDetail : orderDetails) {
                moneySum += orderDetail.getOrderMoney();
            }
            if (adUser.getAdMoney() < moneySum) {
                return ResultUtil.error("账号余额不足，请及时充值！");
            }
            List<String> phones=new ArrayList<>();
            for (OrderDetail orderDetail : orderDetails) {
                String adId = orderDetail.getAdId();
                Gzh gzh = gzhMapper.selectByGhId(orderDetail.getGhId());
                Record record1 = new Record();
                record1.setUserId(orderDetail.getAdId());
                record1.setMoney(orderDetail.getOrderMoney());
                record1.setOrderId(orderDetail.getOrderId());
                record1.setYyName(orderDetail.getNeedName());
                record1.setContent("冻结记录");
                record1.setGzhName(gzh.getGzhName());
                record1.setStatus((byte) 1);
                record1.setUserFz(orderDetail.getUserFz());
                record1.setUserName(orderDetail.getUserName());
                recordService.insertSelective(record1);
                Record record2 = new Record();
                record2.setUserId(orderDetail.getAdId());
                record2.setMoney(orderDetail.getOrderMoney());
                record2.setOrderId(orderDetail.getOrderId());
                record2.setYyName(orderDetail.getNeedName());
                record2.setStatus((byte) 4);
                record2.setGzhName(gzh.getGzhName());
                record2.setContent("消费记录");
                record2.setUserFz(orderDetail.getUserFz());
                record2.setUserName(orderDetail.getUserName());
                recordService.insertSelective(record2);
                log.info(adUserId + "进来万粉订单付款");
                adUserService.updateMoney(adId, orderDetail.getOrderMoney());
                //添加冻结金额
                adUserService.updateIceMoney(adId, orderDetail.getOrderMoney());
                MtUser mtUser = mtUserMapper.selectByMtUserId(orderDetail.getMtId());
                if(!phones.contains(mtUser.getMtPhone())){
                    phones.add(mtUser.getMtPhone());
                }
            }
            for (String phone:phones) {
                NoteUtil.getNote(phone);
            }
            orderMapper.updateStatus((byte) 1, orderDetails.get(0).getHostId(),null);
            //把订单状态改为待响应
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setStatus((byte) 1);
            orderDetail.setPayTime(now());
            orderDetail.setHostId(gzhVo.getHostId());
            orderDetailMapper.updateByPrimaryKeySelective(orderDetail);
            return ResultUtil.success();
        }
        return ResultUtil.error("无token!");
    }


    /**
     * 广告||媒体查询订单内的详情和推广内容
     * @param map
     * @return
     */
    @PostMapping("getDetails")
    public Result getDetails(@RequestBody Map<String, String> map){
        String adtoken = map.get("adUserToken");
        String adUserId = null;
        String mtUserId = null;
        if (adtoken != null) {
            adUserId = TokenUtilT.getTokenById(adtoken);
        } else {
            String mttoken = map.get("mtUserToken");
            mtUserId = TokenUtilT.getTokenById(mttoken);
        }
        List<OrderDetail> orderDetails = orderDetailMapper.getDetails(map.get("hostId"), adUserId, mtUserId);
        for (OrderDetail orderDetail : orderDetails) {
            Base64.Decoder decoder = Base64.getDecoder();
            orderDetail.setTextBody(new String(decoder.decode(orderDetail.getTextBody()), StandardCharsets.UTF_8));
        }
        return ResultUtil.success(orderDetails.get(0));
    }


    /**
     * 广告方导出要预约了公众号
     * @param
     * @return
     */
    @GetMapping("exportOrderGzh")
    public void exportOrderGzh(@RequestParam("adUserToken") String token, @RequestParam("hostId") String hostId, HttpServletResponse response) throws IOException {
        String adUserId = TokenUtilT.getTokenById(token);
        List<OrderNew> orderDetailList = orderDetailMapper.selectByAdIdAndStatus(adUserId,9,null,null,
                null,hostId,null,null);
        EasyPoiUtil.exportExcel(orderDetailList,"已预约公众号","sheet1",OrderNew.class,"已预约公众号.xls",true,response);
    }


    /**
     * 广告方查询大订单状态条数
     * @param adUserVo
     * @return
     */
    @PostMapping("getAdCount")
    public Result getAdCount(@RequestBody AdUserVo adUserVo){
        String adUserId = TokenUtilT.getTokenById(adUserVo.getAdUserToken());
        AdUser adUser = adUserMapper.selectByAdUserId(adUserId);
        if (adUser != null) {
            return orderDetailService.getAdCount(adUserId);
        }
        return ResultUtil.error("无token!");
    }

    /**
     * 媒体方查询大订单状态条数
     * @param mtUserVo
     * @return
     */
    @PostMapping("getMtCount")
    public Result getMtCount(@RequestBody MtUserVo mtUserVo){
         String mtUserId = TokenUtilT.getTokenById(mtUserVo.getMtUserToken());
         MtUser mtUser = mtUserService.selectByMtUserId(mtUserId);
         if (mtUser != null) {
             return orderDetailService.getMtCount(mtUserId);
         }
         return ResultUtil.error("无token!");
    }



    }
